/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

export function levelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const arr: number[][] = [];
  let nodeArr: TreeNode[] = [];
  nodeArr.push(root);
  while (nodeArr.length) {
    const len = nodeArr.length;
    const temp: number[] = [];
    for (let index = 0; index < len; index++) {
      const node = nodeArr.shift();
      temp.push(node.val);
      if(node.left) nodeArr.push(node.left)
      if(node.right) nodeArr.push(node.right)
    }
    arr.push(temp)
  }

  return arr;
}
